﻿using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using SimpleTasks.Domain.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleTasks.Persistence.Hibernate
{
   class HibernateHelper
   {
      private static ISessionFactory _currentSessionFactory;

      internal static ISession OpenSession()
      {
         return BuildSessionFactory().OpenSession();
      }

      internal static ISessionFactory BuildSessionFactory()
      {
         if (_currentSessionFactory == null)
         {
            var hibernateConfiguration =
               Fluently.Configure()
                  .Database(
                     MsSqlConfiguration.MsSql2008
                        .ConnectionString(builder => builder
                        .Server(@"localhost\SQLEXPRESS")
                        .Database("SimpleTasks")
                        .TrustedConnection())
                     .ShowSql())
                  .Mappings(m => m.FluentMappings.AddFromAssemblyOf<SimpleTask>());

            hibernateConfiguration.ExposeConfiguration(c => c.SetProperty("generate_statistics", "true"));

            _currentSessionFactory = hibernateConfiguration.BuildSessionFactory();
         }

         return _currentSessionFactory;
      }
   }
}
